﻿using DFGK.IService;
using DFGK.Service;
using DFGK_WMS.Common;
using DFGK_WMS.Model.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.VisualBasic;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.Collections.Generic;
using System.Net.Mime;
using System.Security.Claims;

namespace DFGK_WMS.WebAPI.Controllers.PC.装备维修管理
{
    /// <summary>
    /// 装备编号管理、装备基本信息、信息化名称库、装备品牌库、装备规格型号库
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    [ApiExplorerSettings(GroupName = "PC")]
    public class EquipmentBasicController : BaseController
    {
        private readonly IEquipmentBasicService equipmentBasicService;
        /// <summary>
        /// 装备信息管理
        /// </summary>
        /// <param name="environment"></param>
        /// <param name="equipmentBasicService"></param>
        public EquipmentBasicController(IWebHostEnvironment environment, IEquipmentBasicService equipmentBasicService) : base(environment)
        {
            this.equipmentBasicService = equipmentBasicService;
        }
        /// <summary>
        /// 查询装备信息管理
        /// </summary>
        /// <param name="name">调拨装备的名称</param>
        /// <param name="pageIndex">当前页码</param>
        /// <param name="pageSize">每页条数</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetAllEquipmentBasic(string? name, int pageIndex = 1, int pageSize = 5)
        {
            if (pageIndex <= 0 || pageSize <= 0)
            {
                BaseResult.Result("400", "分页条件有误！");
            }
            var list = equipmentBasicService.GetEquipmentBasic(name, pageIndex, pageSize, out var totalCount);
            if (list != null)
            {
                return Ok(BaseResult.Result(list, "查询成功！", "200", totalCount));
            }
            return Ok(BaseResult.Result(null, "查询失败！", "500", 0));
        }

        /// <summary>
        /// 根据装备id查询装备信息管理
        /// </summary>
        /// <param name="id">装备id</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetEquipmentBasicById(long id)
        {
            if (id <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            var obj = equipmentBasicService.GetEquipmentBasicById(id);
            if (obj != null)
            {
                return Ok(BaseResult.Result(obj, "查询成功！", "200", 0));
            }
            return Ok(BaseResult.Result(null, "查询失败！", "500", 0));
        }

        /// <summary>
        /// 添加装备信息
        /// </summary>
        /// <param name="equipmentBasic">装备信息实体类</param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddEquipmentBasic(EquipmentBasic equipmentBasic)
        {
            if (string.IsNullOrEmpty(equipmentBasic.Name) || equipmentBasic.Name.Length <= 0)
            {
                return Ok(BaseResult.Result("400", "名称不能为空！"));
            }
            equipmentBasic.CreateUserId = base.BaseGetNowUserId();
            equipmentBasic.CreateUserName = base.BaseGetNowUserName();

            var res = equipmentBasicService.AddEquipmentBasic(equipmentBasic);
            if (res)
            {
                return Ok(BaseResult.Result(true, "添加成功", "200"));
            }
            return Ok(BaseResult.Result(false, "添加失败", "500"));
        }
        /// <summary>
        /// 修改装备信息管理
        /// </summary>
        /// <param name="EquipmentBasic">装备信息管理实体类</param>
        /// <returns></returns>
        [HttpPut]
        public IActionResult UpdEquipmentBasic(EquipmentBasic EquipmentBasic)
        {
            if (EquipmentBasic.Id <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            if (string.IsNullOrEmpty(EquipmentBasic.Name))
            {
                return Ok(BaseResult.Result("400", "必填项不能为空！"));
            }
            var res = equipmentBasicService.UpdEquipmentBasic(EquipmentBasic);
            if (res)
            {          
                return Ok(BaseResult.Result(true, "修改成功", "200"));
            }
            return Ok(BaseResult.Result(false, "修改失败", "500"));
        }
        /// <summary>
        /// 删除装备信息管理
        /// </summary>
        /// <param name="id">装备信息管理id</param>
        /// <returns></returns>
        [HttpDelete]
        public IActionResult DelEquipmentBasic(long id)
        {
            if (id <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            var res = equipmentBasicService.DelEquipmentBasic(id);
            if (res)
            {         
                return Ok(BaseResult.Result(true, "删除成功", "200"));
            }
            return Ok(BaseResult.Result(false, "删除失败", "500"));
        }


        /// <summary>
        /// 装备编号导入
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult MaterialCategoryDown(IFormFile file)
        {
            try
            {
                // 检查文件是否为空
                if (file == null || file.Length == 0)
                {
                    return Ok(BaseResult.Result("400", "没有选择文件或文件为空"));
                }
                string message = "";
                var postFile = Request.Form.Files[0];
                string extName = Path.GetExtension(postFile.FileName);
                if (!new string[] { ".xls", ".xlsx" }.Contains(extName))
                {
                    return Ok(BaseResult.Result("400", "必须是Excel文件"));
                }
                string uname = HttpContext.User.FindFirstValue("UserName");
                int uid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
                MemoryStream ms = new MemoryStream();
                postFile.CopyTo(ms);
                ms.Position = 0;
                IWorkbook wb = null;
                if (extName.ToLower().Equals(".xls")) // 97-2003版本
                {
                    wb = new HSSFWorkbook(ms);
                }
                else
                {
                    wb = new XSSFWorkbook(ms); // 2007以上版本
                }

                ISheet sheet = wb.GetSheetAt(0);

                //总行数（0开始）
                int totalRow = sheet.LastRowNum;
                // 总列数（1开始）
                int totalColumn = sheet.GetRow(0).LastCellNum;

                List<EquipmentBasic> stuList = new();
                for (int i = 1; i <= totalRow; i++)
                {

                    IRow row = sheet.GetRow(i);
                    string? EquipmentName = row.GetCell(0)?.StringCellValue;
                    string? EquipmentCode = row.GetCell(1)?.StringCellValue;
                    string? ModelName = row.GetCell(2)?.StringCellValue;
                    string? SpecificationModel = row.GetCell(3)?.StringCellValue;

                    var equ = new EquipmentBasic
                    {
                        Code = EquipmentCode,
                        Name = EquipmentName,
                        ModelName = ModelName,
                        SpecificationModel = SpecificationModel,
                    
                    };
                    stuList.Add(equ);
                }
                if (stuList.Count <= 0)
                {
                    //message = "文件信息为空或别写字段为空！";
                    return Ok(BaseResult.Result(false, "导入失败！" + message, "500"));
                }
                bool result = equipmentBasicService.AddEquipment(stuList);
                wb.Close();
                if (result)
                {
                    return Ok(BaseResult.Result(true, "导入成功！" + message, "200"));
                }
                return Ok(BaseResult.Result(stuList, "导入失败！", "500"));
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 装备编号导出
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult EquipmentBasicDown()
        {
            var list = equipmentBasicService.GetEquipmentBasic();
            if (list != null)
                return EquipmentBasicDown(list);
            else
                return Ok();
        }

        /// <summary>
        /// 装备编号信息导出
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult EquipmentBasicMsgDown()
        {
            var list = equipmentBasicService.GetEquipmentBasicMsgDowns();
            if (list != null)
                return EquipmentBasicMsgDown(list);
            else
                return Ok();
        }

        /// <summary>
        /// 采购订单导出
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult PurchaseOrderDown()
        {
            var list = equipmentBasicService.GetPurchaseOrderDown();
            if (list != null)
                return PurchaseOrderDown(list);
            else
                return Ok();
        }


    }
}
